//
//  HomePageController.m
//  SouthChina
//
//  Created by zorro on 15/6/11.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "HomePageController.h"
#import "WeatherView.h"
#import "SESpringBoard.h"
#import "PublicAccount.h"
#import "XLCycleScrollView.h"
#import "BillboardTableViewCell.h"
#import "AddButtonPullDownView.h"
#import "AddFriendViewController.h"
#import "ZbarReaderViewController.h"
#import "FeedbackViewController.h"
#import "MessageSessionDao.h"
#import "TakePhotoController.h"
#import "TabbarViewController.h"
#import "TabbarView.h"
#import "PersonalCenterViewController.h"
#import "WeatherData.h"
#import "CreateGroupViewController.h"
#import "DataDictDao.h"
#import "PersonalCenterTableViewCell.h"


@interface HomePageController () <UITableViewDataSource,UITableViewDelegate>
{
    WeatherView * we;
    
    NSMutableArray *_dateList;
    NSMutableArray* homeAPP;
    NSArray *Poptitles;
    NSInteger currentIndex;//当前选中索引值
    NSArray * titles; //标题列表
    DataDict *dicttype;
    NSTimer * _timer;
    NSTimer * _timerEX;//如果定位开始没成功，则默认去读一次数据库
    BOOL bStartWeather;
}
@end

@implementation HomePageController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //接收公众号关注发生变化的时候广播
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealPublicAttentionNotifier:) name:PUBLIC_ATTENTION_BROADCAST object:nil];
        //接收天气数据重新加载广播消息
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWeatherChangeNotifier:) name:WEATHER_CHANGE_BROADCAST object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ScanLoginMsg:) name:SCAN_LOGIN_MSG object:nil];
    }
    return self;
}

-(void)ScanLoginMsg:(NSNotification*)notification
{
    if (notification.object !=nil) {
        if([notification.object rangeOfString:@"1"].location != NSNotFound){
            [self  showAlerHUD:[notification.object stringByReplacingOccurrencesOfString:@"1" withString:@""]];}
    }
    
}

-(void)dealPublicAttentionNotifier:(NSNotification*)notification
{
    if (notification.object !=nil) {
         NSLog(@"%@",notification.object);
        [self showAlerHUD:notification.object];
    }
   
    [self LoadApps];
}

-(void)dealWeatherChangeNotifier:(NSNotification*)notification
{
    NSLog(@"重新加载天气");
    [self refreshWeatherData];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    Poptitles = @[@"添加朋友",@"扫一扫",@"意见反馈"];
    //设置背景，必须啊，默认透明，搞不好上一层加载你的页面是个黑黑就完了···
    self.view.backgroundColor = [UIColor whiteColor];
    bStartWeather = FALSE;
   
    //请按顺序加载····
    [self LoadHead];
    
    [self LoadWeather];
    
    [self LoadApps];
    
    //定时刷新天气（每间隔1小时开启一次定位60*60）
    _timer = [NSTimer scheduledTimerWithTimeInterval:3600 target:self selector:@selector(refreshWeatherDataMsg) userInfo:nil repeats:YES];
    //双保险如果百度地区都不服务，主动去调用天气预报数据
    _timerEX = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(DefaultWeatherDataMsg) userInfo:nil repeats:YES];
}

-(void)refreshWeatherDataMsg
{
     NSLog(@"XXXXXXXXXXXXXXXXXX 刷新天气命令");
    [[NSNotificationCenter defaultCenter] postNotificationName:WEATHER_REFRESH_BROADCAST object:nil];
}

-(void)DefaultWeatherDataMsg
{
    //如果一分钟还没有天气预报消息，则主动去读数据库中天气预报数据
    NSLog(@"........主动去读数据库中天气预报数据");
    NSDictionary * weatherData = [[NSUserDefaults standardUserDefaults] objectForKey:@"WeatherData"];
    if(weatherData==nil)
    {
        NSLog(@"yyyyy主动去读数据库中天气预报数据");
        [self GetWeatherData:@"长沙"];
    }
    [_timerEX invalidate];
}

-(void) GetWeatherData:(NSString *)sCity{
    //默认
    if([sCity isEqualToString:@""])
        sCity=@"长沙";
    
    NSLog(@"城市：%@",sCity);
    NSDictionary *params = @{@"cityName":sCity};
    
    [DE serverCall:@"queryWeather" params:params callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        NSMutableDictionary *weather = [NSMutableDictionary dictionary];
        if(success)
        {
            if(data )
            {
                [weather addEntriesFromDictionary:[data objectForKey:@"weather"]];
                [weather setObject:sCity forKey:@"city"];
                //天气图片
                [[NSUserDefaults standardUserDefaults] setObject:weather forKey:@"WeatherData"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                //获取数据后，需要重新刷新首页
                [[NSNotificationCenter defaultCenter] postNotificationName:WEATHER_CHANGE_BROADCAST object:nil];
            }
        }
    }];
}


//刷新天气数据
-(void)refreshWeatherData
{
    NSDictionary * weatherData = [[NSUserDefaults standardUserDefaults] objectForKey:@"WeatherData"];
    
    WeatherData * wd = [[WeatherData alloc]initWithData:weatherData];
    NSURL *url= [NSURL URLWithString: [wd.weatherPic hasPrefix:@"http"]?wd.weatherPic:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,wd.weatherPic]];
    
    [we.weatherImg setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
    we.labTPRange.text = [NSString stringWithFormat:@"%@-%@°C",wd.lTemp, wd.hTemp ];
    we.labcity.text = wd.city;
    NSString *sTmp = wd.temp;
    //测试：
    //sTmp = @"-24";
    int ntmp = [sTmp intValue];
    we.tmp3Image.hidden = YES;
    //零度以下特殊处理()
    if (ntmp<0) {
        we.tmp3Image.hidden = NO;
        if(sTmp.length==3)
        {
            NSString *STMP1 = [sTmp substringWithRange:NSMakeRange(1,1)];
            NSString *STMP2 = [sTmp substringWithRange:NSMakeRange(2,1)];
            we.tmp3Image.image = [UIImage imageNamed:@"minus.png"];
            we.tmp2Image.image = [UIImage imageNamed:[NSString stringWithFormat:@"n%@.png",STMP1]];
            we.tmp1Image.image = [UIImage imageNamed:[NSString stringWithFormat:@"n%@.png",STMP2]];
            we.leadImage3Contranit.constant = 4;
           
        }
        if (sTmp.length==2) {
            NSString *STMP1 = [sTmp substringWithRange:NSMakeRange(1,1)];
            we.tmp3Image.image = [UIImage imageNamed:@"minus.png"];
            we.tmp1Image.image = [UIImage imageNamed:[NSString stringWithFormat:@"n%@.png",STMP1]];
            we.tmp2Image.hidden = YES;
            we.leadImage3Contranit.constant = 36;
        }
    }
    else //0以上
    {
        if(sTmp.length==1)
        {
            we.tmp1Image.image = [UIImage imageNamed:[NSString stringWithFormat:@"n%@.png",sTmp]];
            we.tmp2Image.hidden = YES; //隐藏
        }
        else
        {
            NSString *STMP0 = [sTmp substringWithRange:NSMakeRange(0,1)];
            NSString *STMP1 = [sTmp substringWithRange:NSMakeRange(1,1)];
            we.tmp1Image.image = [UIImage imageNamed:[NSString stringWithFormat:@"n%@.png",STMP1]];
            we.tmp2Image.image = [UIImage imageNamed:[NSString stringWithFormat:@"n%@.png",STMP0]];
            we.tmp2Image.hidden = NO;
        }
    }
}

-(void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:PUBLIC_ATTENTION_BROADCAST object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:WEATHER_CHANGE_BROADCAST object:nil];
    
    [_timer invalidate];
}
/**
 *	@brief 加载导航栏
 */
- (void)LoadHead
{
    [self.navigationController setNavigationBarHidden:YES];
    
    [self addTitleBarWithBackBtn:@""];
    
    //导航栏上面的+号按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(258.0f, (YNEW), 60.0f, 40.0f);
    [rightBtn addTarget:self action:@selector(showRightBtnView:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"addfriend_group_flag"] forState:UIControlStateNormal];
    //[rightBtn setBackgroundColor:[UIColor redColor]];
    //rightBtn.imageEdgeInsets = UIEdgeInsetsMake ( 5 ,  10 , 5 , 10 );
    
    [self.titlebar addSubview:rightBtn];
    [self addUserWorkStatus];
    [self addHeadImage];
}

-(void)addUserWorkStatus{
    //导航栏上增加选择工作状态按钮
    _WorkStatusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _WorkStatusBtn.frame = CGRectMake(120.0f, (YNEW)+12, 48.0f, 24.0f);
    [_WorkStatusBtn addTarget:self action:@selector(WorkStatusBtnView:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *img=[UIImage imageNamed:@"index_drop.png"];
    [_WorkStatusBtn setBackgroundImage:img forState:UIControlStateNormal];
    _WorkStatusBtn.titleLabel.font = [UIFont systemFontOfSize: 12.0];
    [self.titlebar addSubview:_WorkStatusBtn];
    
    //读取用户状态
    NSString *userstate = [DE getGlobalVar:LOGIN_USER_WORKSTATUS] == nil?@"":[DE getGlobalVar:LOGIN_USER_WORKSTATUS];
    if([userstate isEqualToString:@""])
        userstate = @"空闲";
     NSLog(@"*************00000用户状态:%@",userstate);
    [_WorkStatusBtn setTitle:userstate forState: UIControlStateNormal];
    
    //查询工作状态数据字典
    currentIndex = -1;
    NSString *sql = [NSString stringWithFormat:@"where dicttypeId ='7'" ];
    titles = [DataDictDao queryDataDict:sql];
    
    if(![userstate isEqualToString:@""])
    {
        for(NSInteger i = 0;i<titles.count;i++)
        {
            DataDict *dict =[titles objectAtIndex:i];
            if ([userstate isEqualToString:dict.dictdataValue] ) {
                currentIndex = i;
                dicttype = dict;
                break;
            }
        }
    }
    
    
}

-(void)refreshWorkStuts{
    //读取用户状态
    NSString *userstate = [DE getGlobalVar:LOGIN_USER_WORKSTATUS] == nil?@"":[DE getGlobalVar:LOGIN_USER_WORKSTATUS];
    if([userstate isEqualToString:@""])
        userstate = @"空闲";
    
    [_WorkStatusBtn setTitle:userstate forState: UIControlStateNormal];
    
    //查询工作状态数据字典
    NSString *sql = [NSString stringWithFormat:@"where dicttypeId ='7'" ];
    titles = [DataDictDao queryDataDict:sql];
    
    if(![userstate isEqualToString:@""])
    {
        for(NSInteger i = 0;i<titles.count;i++)
        {
            DataDict *dict =[titles objectAtIndex:i];
            if ([userstate isEqualToString:dict.dictdataValue] ) {
                currentIndex = i;
                dicttype = dict;
                break;
            }
        }
    }

}

-(void)showRightBtnView:(id)sender
{
    CGFloat xWidth = self.view.bounds.size.width - 162.0f;
    CGFloat yHeight = 120.0f;
    UIPopoverListView *poplistview = [[UIPopoverListView alloc] initWithFrame:CGRectMake(0, 0, xWidth, yHeight)];
    poplistview.delegate = self;
    poplistview.datasource = self;
    poplistview.listView.scrollEnabled = YES;
    poplistview.tag = 101;
    poplistview.center = CGPointMake(240,130);
    [poplistview show];
}

-(void)WorkStatusBtnView:(id)sender
{
    CGFloat xWidth = self.view.bounds.size.width - 190.0f;
    CGFloat yHeight = 160.0f;
    UIPopoverListView *poplistview = [[UIPopoverListView alloc] initWithFrame:CGRectMake(0, 0, xWidth, yHeight)];
    poplistview.delegate = self;
    poplistview.datasource = self;
    poplistview.listView.scrollEnabled = YES;
    poplistview.tag = 102;
    poplistview.center = CGPointMake(150,150);
    [poplistview show];
}


#pragma mark - UIPopoverListViewDataSource


- (UITableViewCell *)popoverListView:(UIPopoverListView *)popoverListView cellForIndexPath:(NSIndexPath *)indexPath
{
    if(popoverListView.tag==101)
    {
        static NSString *identifier = @"cell";
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] ;
        cell.textLabel.text = Poptitles[indexPath.row];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.textColor = [UIColor colorWithRed:85.0f/255.0f green:85.0f/255.0f blue:85.0f/255.0f alpha:1.0f];
        return cell;

    }else
    {
        static NSString * CellIdentifier = @"PersonalCenterTableViewCell";
        PersonalCenterTableViewCell *cell = [[PersonalCenterTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
        
        UIImageView *cellimage =  [[UIImageView alloc] initWithFrame:CGRectMake(15, 15,10, 10)];
        UILabel * titlaLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 10, 100, 20)];
        cellimage.image = [UIImage imageNamed:@"单选选中.png"];
        [cell addSubview:cellimage];
        cellimage.hidden = YES;
        
        titlaLabel.textColor = [UIColor colorWithRed:85.0f/255.0f green:85.0f/255.0f blue:85.0f/255.0f alpha:1.0f];
        titlaLabel.textAlignment = NSTextAlignmentLeft;
        titlaLabel.font = [UIFont boldSystemFontOfSize:14.0f];
        [cell addSubview:titlaLabel];
        DataDict *dict =[titles objectAtIndex:indexPath.row];
        titlaLabel.text = dict.dictdataValue;
        
        if(currentIndex == indexPath.row)
        {
             cellimage.hidden = NO;
        }
        return cell;
    }
}


- (NSInteger)popoverListView:(UIPopoverListView *)popoverListView
       numberOfRowsInSection:(NSInteger)section
{
    if(popoverListView.tag==101)
        return Poptitles.count;
    else
        return titles.count;
}

#pragma mark - UIPopoverListViewDelegate
- (void)popoverListView:(UIPopoverListView *)popoverListView
     didSelectIndexPath:(NSIndexPath *)indexPath
{
    
    if(popoverListView.tag==101)
    {
        if(indexPath.section==0)
        {
            if(indexPath.row==0) //添加朋友
            {
                AddFriendViewController * addfriend = [[AddFriendViewController alloc] init];
                [kAppDelegate.iCSDrawerController.navigationController pushViewController:addfriend animated:NO];
            }else if(indexPath.row==1)//扫一扫
            {
                ZbarReaderViewController * scanning = [[ZbarReaderViewController alloc] init];
                scanning.srootVC = @"1";
                [kAppDelegate.iCSDrawerController.navigationController pushViewController:scanning animated:NO];
            }else if(indexPath.row==2)//意见反馈
            {
                FeedbackViewController * feedback = [[FeedbackViewController alloc] init];
                [kAppDelegate.iCSDrawerController.navigationController pushViewController:feedback animated:NO];
            }
        }
    }
    else{
        currentIndex = indexPath.row;
        dicttype =[titles objectAtIndex:indexPath.row];
        //更新工作状态
        [_WorkStatusBtn setTitle:dicttype.dictdataValue forState: UIControlStateNormal];
        //调用接口更新状态
        NSDictionary *map = @{@"workStatus":dicttype.dictdataValue};
        [DE serverCall:@"updateUserInfo" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
            if(success)
            {
                [DE setGlobalVar:LOGIN_USER_WORKSTATUS value:dicttype.dictdataValue];
                [super btnBack];
            }
            else{
                [self showAlerHUD:@"提交失败！"];
            }
            //刷新工作状态 20151012
            [self refreshWorkStuts];
        }];
        
    }
}

- (CGFloat)popoverListView:(UIPopoverListView *)popoverListView
   heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40.0f;
}

-(void) reloadDate{
    
    //[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary *dict  = [[NSDictionary alloc] init];
    
    NSDictionary* cacheDate = [DE serverCall:@"queryGuestNews" params:dict callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        dispatch_async(dispatch_get_main_queue(), ^{
            //[MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if (success) {
                _dateList  = [[NSMutableArray alloc] initWithArray:[data objectForKey:@"articles"]];          
                    
                
                [we.Billboard reloadData];
                
            }else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:desc delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }
        });
        
    }needCache:YES];
    
    if(cacheDate){
        _dateList  = [[NSMutableArray alloc] initWithArray:[cacheDate objectForKey:@"articles"]];
       [we.Billboard reloadData];
    }
}

- (void)didClickPage:(XLCycleScrollView *)csView atIndex:(NSInteger)index
{
    WebViewController * detail = [[WebViewController alloc] init];
    detail.webUrl = [ _dateList[index] objectForKey:@"Url"];

    [kAppDelegate.iCSDrawerController.navigationController pushViewController:detail animated:YES];
}

- (NSString*)weekdayStringFromDate
{
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"星期天", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:[NSDate date]];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM月dd号"];
    
    NSString* sdate = [NSString stringWithFormat:@"%@ %@",[dateFormatter stringFromDate:[NSDate date]],[weekdays objectAtIndex:theComponents.weekday]];
    return sdate;
    
}
- (void)LoadWeather {
    NSLog(@"$$$$$$$$$$$$$$$$$$$$$$$$$$ LoadWeather");
    
    we = [[[NSBundle mainBundle] loadNibNamed:@"WeatherView" owner:self options:nil] objectAtIndex:0];
    
    //we.frame = (CGRect){0, TITLE_BAR_HEGIHT+YNEW,SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW-TABBARHEIGHT};
     we.frame = (CGRect){0, self.titlebar.frame.origin.y+self.titlebar.frame.size.height,SCREEN_WIDTH, SCREEN_HEIGHT-self.titlebar.frame.size.height-YNEW};
    
    
    we.Billboard.tableHeaderView =we.headview;
    
    NSDictionary * weatherData = [[NSUserDefaults standardUserDefaults] objectForKey:@"WeatherData"];
    
   WeatherData * wd = [[WeatherData alloc]initWithData:weatherData];
   NSURL *url= [NSURL URLWithString: [wd.weatherPic hasPrefix:@"http"]?wd.weatherPic:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,wd.weatherPic]];
   
    [we.weatherImg setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
    we.labTPRange.text = [NSString stringWithFormat:@"%@-%@°C",wd.lTemp, wd.hTemp ];
    we.labcity.text = wd.city;
    NSString *sTmp = wd.temp;
    //测试：
    //sTmp = @"-24";
    int ntmp = [sTmp intValue];
    we.tmp3Image.hidden = YES;
    //零度以下特殊处理()
    if (ntmp<0) {
        we.tmp3Image.hidden = NO;
        if(sTmp.length==3)
        {
            NSString *STMP1 = [sTmp substringWithRange:NSMakeRange(1,1)];
            NSString *STMP2 = [sTmp substringWithRange:NSMakeRange(2,1)];
            we.tmp3Image.image = [UIImage imageNamed:@"minus.png"];
            we.tmp2Image.image = [UIImage imageNamed:[NSString stringWithFormat:@"n%@.png",STMP1]];
            we.tmp1Image.image = [UIImage imageNamed:[NSString stringWithFormat:@"n%@.png",STMP2]];
            we.leadImage3Contranit.constant = 4;
        }
        if (sTmp.length==2) {
            NSString *STMP1 = [sTmp substringWithRange:NSMakeRange(1,1)];
            we.tmp3Image.image = [UIImage imageNamed:@"minus.png"];
            we.tmp1Image.image = [UIImage imageNamed:[NSString stringWithFormat:@"n%@.png",STMP1]];
            we.tmp2Image.hidden = YES;
            we.leadImage3Contranit.constant = 36;
        }
    }
    else //0以上
    {
        if(sTmp.length==1)
        {
            we.tmp1Image.image = [UIImage imageNamed:[NSString stringWithFormat:@"n%@.png",sTmp]];
            we.tmp2Image.hidden = YES;
        }
        else
        {
            NSString *STMP0 = [sTmp substringWithRange:NSMakeRange(0,1)];
            NSString *STMP1 = [sTmp substringWithRange:NSMakeRange(1,1)];
            we.tmp1Image.image = [UIImage imageNamed:[NSString stringWithFormat:@"n%@.png",STMP1]];
            we.tmp2Image.image = [UIImage imageNamed:[NSString stringWithFormat:@"n%@.png",STMP0]];
            we.tmp2Image.hidden = NO;
        }
    }
    [self.view addSubview:we];
    [self reloadDate];
    we.Billboard.dataSource = self;
    we.Billboard.delegate = self;
   
}

/**
 *	@brief	加载应用列表
 */
- (void)LoadApps {
    //查询首页应用列表
    homeAPP =   [NSMutableArray arrayWithArray:[PublicAccountDao getHomePublicAccount]];
    //根据userSort从小到大排序
    [self SortArray:homeAPP orderWithKey:@"userSort" ascending:YES];
    NSMutableArray *items = [NSMutableArray array];
    for (int i = 0; i< homeAPP.count ; i++) {
        PublicAccount * publicaccount = [homeAPP objectAtIndex:i];
        NSURL *url= [NSURL URLWithString: [publicaccount.headImg hasPrefix:@"http"]?publicaccount.headImg:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,publicaccount.headImg]];
        NSString *appName = publicaccount.appName;
        //是否为官方
        BOOL isOffical =[@"1" isEqualToString:[publicaccount getValue:@"isOfficial"]];
        
        NSString *sessonid = [NSString stringWithFormat:@"p2p_%@",publicaccount.appId];
        MessageSession *appSession = [MessageSessionDao queryMsgSessionById:sessonid];
        
        NSString *badgeValue =@"0";
        if (appSession) {
            //20151012
            if(appSession.badgeNumber>99)
                badgeValue = [NSString stringWithFormat:@"%d+",99];
            else
                badgeValue = [NSString stringWithFormat:@"%d",appSession.badgeNumber];
        }
        BOOL canremov = [publicaccount.isBasic isEqualToString:@"1"]?NO:YES;
        [items addObject:[[SEMenuItem alloc]initWithFrame:CGRectMake(0,0,72,72) WithTitle:appName imageName:@"empty_photo" imageUrl:url badgeValue:badgeValue removable:canremov Offical:isOffical canCauseRemoveAction:YES]];
        //设置标签
        [ (SEMenuItem*)[items objectAtIndex:i] setTag:i];
        
    }
    //增加一个添加按钮
    [items addObject:[[SEMenuItem alloc]initWithFrame:CGRectMake(0,0,72,72) WithTitle:@"添加" imageName:@"add.png" imageUrl:nil badgeValue:@"0" removable:NO Offical:NO canCauseRemoveAction:NO]];
    [(SEMenuItem*)[items lastObject] setTag:9999];
    
    we.board.items = items;
    we.board.delegate = self;
    [we.board reloadViews];
    
    //更新头像和用户名
    [self refreshImagehead];
    //更新工作状态
    [self refreshWorkStuts];
    NSLog(@"刷新刷新");
}

//dicArray：待排序的NSMutableArray。
//key：按照排序的key。
//yesOrNo：升序或降序排列，yes为升序，no为降序。
-(void) SortArray:(NSMutableArray *)dicArray orderWithKey:(NSString *)key ascending:(BOOL)yesOrNo{
    NSSortDescriptor *distanceDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:yesOrNo];
    NSArray *descriptors = [NSArray arrayWithObjects:distanceDescriptor,nil];
    [dicArray sortUsingDescriptors:descriptors];
}

-(void)longPressMenuItem:(SESpringBoard *)springBoard
{
    NSLog(@"长按某个应用");
    //跳转到一个排序页面
    AppSortViewController * appSort = [[AppSortViewController alloc] init];
    appSort.APPList = homeAPP;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:appSort animated:NO];
}

-(void)springBoardMenuItemClicked:(SESpringBoard *)springBoard WithTag:(int)tag withTitle:(NSString *)title
{
    if(tag == homeAPP.count)//app应用列表中添加按钮事件
    {
        NSLog(@"&&&&&&&&&&&&&&跳转到应用市场");
        //跳转到应用市场
        TabbarViewController * tab = (TabbarViewController *) kAppDelegate.iCSDrawerController.centerViewController;
        [tab.tabbar.tabbar selectItemAtIndex:3];
    }
    else
    {        
       PublicAccount *publicAccount  = [homeAPP objectAtIndex:tag];
       MessageViewController * message = [[MessageViewController alloc] init];
            NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2P,@"messtype":@"3",@"record_DB_ID":publicAccount.appId,
                                   @"recordID":publicAccount.appId};
       message.sessInfo = dicc;
       [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];
        
        
    }
    
}
-(void)springBoardMenuItemRemoved:(SESpringBoard *)springBoard withTag:(int)tag withTitle:(NSString *)title
{
    NSLog(@"清除应用》》》》》》》》》》");
    //清理主页的应用
    PublicAccount *publicAccount  = [homeAPP objectAtIndex:tag];
    [publicAccount setIsHomeApp:NO];
    [PublicAccountDao updatePublicAccount:publicAccount];
    [homeAPP removeObjectAtIndex:tag];
    //发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:HOMEAPP_CHANGE_BROADCAST object:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//列表设置
//根据分组返回每组的数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dateList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BillboardTableViewCell *l = [[[NSBundle mainBundle] loadNibNamed:@"BillboardTableViewCell" owner:self options:nil] objectAtIndex:0];
    NSURL *url = [NSURL URLWithString: [_dateList[indexPath.row] objectForKey:@"PicUrl"]];
    [l.image setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
    
    l.labContent.text=[ _dateList[indexPath.row] objectForKey:@"Title"];
    l.labDigest.text =[ _dateList[indexPath.row] objectForKey:@"Description"];
    if (indexPath.row == 0) {
        NSString * str=[ _dateList[indexPath.row] objectForKey:@"Title"];
        NSLog(@"xxxxxxxx %@",str);
    }
    return l;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WebViewController * detail = [[WebViewController alloc] init];
    detail.webUrl = [ _dateList[indexPath.row] objectForKey:@"Url"];
    
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:detail animated:YES];
    
     NSString * str=[ _dateList[indexPath.row] objectForKey:@"Title"];
     NSLog(@"DAFJLAFJDLAF %@",str);
    [tableView reloadData];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

//重写提示效果(个性化)
-(void)showAlerHUD:(NSString*)text
{
    BDKNotifyHUD * hudex = [[BDKNotifyHUD alloc] initWithImageEX:[UIImage imageNamed:@""]  text:text hudWidth:70.0f];
    hudex.center = CGPointMake(self.view.center.x,self.view.center.y+200);
    [self.view addSubview:hudex];
    [hudex presentWithDuration:1.5 speed:0.5f inView:self.view completion:^{
        [hudex removeFromSuperview];
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
